<template>
  <t-link
    v-if="!props.batch"
    v-permission="['system:order:transfer-designer']"
    theme="primary"
    @click="handleOpenDialog('update', { ids: props.ids, phone: props.phone })"
  >
    转派设计师
  </t-link>
  <t-button
    v-if="props.batch && props.ids.length"
    v-permission="['system:order:transfer-designer']"
    @click="handleOpenDialog('update', { ids: props.ids, phone: props.phone })"
  >
    转派设计师{{ props.ids.length }}）
  </t-button>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData }"
    :api-map="{ update: transferDesigner }"
    header="转派设计师"
    @request-success="handleDialogRequestSuccess"
  >
    <t-form-item label="设计师" name="designerId" :rules="[{ required: true, message: '请选择设计师' }]">
      <t-select
        v-model:value="formData.designerId"
        :options="designerList"
        :keys="{ label: 'nickname', value: 'id' }"
        placeholder="请选择设计师"
        clearable
        filterable
        @clear="formData.designerId = null"
      />
    </t-form-item>
    <t-form-item
      label="客户手机号码"
      name="phone"
      :rules="[
        { required: !formData.wxCode, message: '请输入手机号码' },
        { telnumber: true, message: '请输入正确的手机号码' },
      ]"
    >
      <t-input v-model:value="formData.phone" placeholder="请输入手机号码" clearable maxlength="11" />
    </t-form-item>
  </custom-dialog>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { PropType, ref, useTemplateRef } from 'vue';

import { transferDesigner } from '@/api/order/basic';
import { getUserListByCompanyIdAndRoleId } from '@/api/system/user';
import CustomDialog from '@/components/custom/dialog/index.vue';

// props
const props = defineProps({
  // 订单ids
  ids: {
    type: Array as PropType<number[]>,
    required: true,
  },
  // 公司id
  companyId: {
    type: Number,
    required: true,
  },
  // 批量
  batch: {
    type: Boolean,
    default: false,
  },
  // 手机号码
  phone: {
    type: String,
    defuault: '',
  },
  // 是否是单品，单品设计师为产品设计师
  isProductDesigner: {
    type: Boolean,
    default: false
  }
});
// emits
const emits = defineEmits(['requestSuccess']);
// 设计师列表
const designerList = ref([]);
// 处理获取设计师列表
const handleGetDesignerList = () => {
  const params = {
    companyId: props.companyId,
    role: props.isProductDesigner?'product_designer':'designer',
  };
  getUserListByCompanyIdAndRoleId(params)
    .then((data) => {
      designerList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetDesignerList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
</script>
